﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Ue.CQRS;
using Ue.CQRS.Results;
using Ue.CQRS.Samples.Domain.EventArgs;

using System.Reflection;

namespace Ue.CQRS.Samples.Domain.Models
{
    public class Book : AggregateRoot
    {
        //考虑聚合根不再聚焦在字段属性上，而是职责 方法和行为上。
        //对于聚合根中的字段，我们只需要那些能够改变业务方法行为的字段(注：状态，只有状态字段能改变业务行为)，其他数据都被归纳入事件对象中
        //所以，我们在这里不应该存在BookProfile对象，它不应该包括在聚合根中，它应该只被归纳到事件对象中
        //private BookProfile profile;
        private Stock stock;

        public Book(string name, string description, string author, string isbn, int paper, int total)
            :base()
        {
            this.BookCreateOnEvent(name, description, author, isbn, paper, total);
        }

        public void UpdateProfile(string name, string description, string author, string isbn, int paper)
        {    
            //进行业务规则判断
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new DomainException("书本名称不能为空，请输入书本名称。");
            }

            if (paper <= 0)
            {
                throw new DomainException("书本页数错误，请重新输入。");
            }

            //执行事件 
            this.BookUpdateProfileOnEvent(name, description, author, isbn, paper);
        }

        public void Remove()
        {
            this.BookRemoveOnEvent(this.ID);
        }

        #region OnEvent and Handler

        [Event]
        private BookCreateEventArgs BookCreateOnEvent(string name, string description, string author, string isbn, int paper, int total)
        {
            return new BookCreateEventArgs(this.ID, name, description, isbn, author, paper, total);
        }

        [Event]
        private BookUpdateProfileEventArgs BookUpdateProfileOnEvent(string name, string description, string author, string isbn, int paper)
        {
            return new BookUpdateProfileEventArgs(this.ID,name, description, isbn, author, paper);
        }

        [Event]
        private Guid BookRemoveOnEvent(Guid id)
        {
            return id;
        }

        [EventHandler]
        private void BookCreateHandle(BookCreateEventArgs eventArgs)
        {
            //this.profile = new BookProfile(eventArgs.Name, eventArgs.Description, eventArgs.Author, eventArgs.ISBN, eventArgs.Pager);
            this.stock = new Stock(eventArgs.Total, eventArgs.Total);
        }

        //[EventHandler]
        //private void BookUpdateProfileHandle(BookUpdateProfileEventArgs eventArgs)
        //{
        //    this.profile = new BookProfile(eventArgs.Name, eventArgs.Description, eventArgs.Author, eventArgs.ISBN, eventArgs.Pager);
        //}

        [EventHandler]
        private void BookRemove(Guid id)
        {
            //删除事件怎么办……
            //是否应该把对象的创建与删除放在领域服务中？
        }

        #endregion
    }
}